import wepy from 'wepy'

export default class extends wepy.mixin {
    config = {}

    data = {
        searchList: [],
        value: '',
        historyList: []
    }

    onLoad() {
        this.historyList = wx.getStorageSync('historyList') || []
        console.log(this.historyList);
    }

    computed = {
        isShowHistory() {
            if (this.value.length == 0) {
                return true
            }
            return false
        }
    }

    methods = {
        // 搜索触发
        onSearch(e) {
            if (this.value.trim().length == 0) {
                return
            }

            // 没有重复在前面追加
            if (this.historyList.indexOf(this.value) == -1) {
                this.historyList.unshift(this.value)
            }
            // 10是结束条件,不会取出来
            this.historyList = this.historyList.slice(0, 10)
            wepy.setStorageSync('historyList', this.historyList)
            console.log(this.historyList);

            wepy.navigateTo({
                url: '/pages/goods_list?query=' + this.value
            })

        },
        // 取消触发
        onCancel() {
            this.searchList = []
        },
        // 输入框变化时触发
        onChange(e) {
            this.value = e.detail
            if (this.value.trim().length == 0) {
                this.searchList = []
                return
            }
            this.getSearchData()
        },

        goGoodsDetail(id) {
            wepy.navigateTo({
                url: '/pages/goods_detail/main?id=' + id
            })
        },

        // 按搜索历史之后展示历史列表
        goGoodsList(query) {
            wepy.navigateTo({
                url: '/pages/goods_list?query=' + query
            })
        },

        clearHistory() {
            this.historyList = []
            wepy.setStorageSync('historyList', [])
        }
    }


    async getSearchData() {
        // 两种传参方式
        // var { data: res } = await wepy.get('/goods/qsearch?query=' + this.value)
        var { data: res } = await wepy.get('/goods/qsearch', { query: this.value })
        console.log(res)

        if (res.meta.status != 200) {
            return wepy.baseToast()
        }
        this.searchList = res.message
        this.$apply()
    }

}